import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Modal, Switch, Form } from 'antd'
const { confirm } = Modal
import UserForm from '../../../components/user-manage/UserForm'
import axios from 'axios'
import { SearchOutlined, DeleteOutlined, ExclamationCircleFilled, EditOutlined } from '@ant-design/icons'
export default function UserList() {
  const [dataSource, setDataSource] = useState<any[]>([])
  const [open, setOpen] = useState(false)
  const [isUpdateVisble, setUpdateVisble] = useState(false)
  // const [form] = Form.useForm()
  const [formValues, setFormValues] = useState()
  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])
  const [updateDisabled, setUpdateDisabled] = useState(false)
  const [current, setCurrent] = useState<any>({})
  const addForm = useRef<any>()
  const updateForm = useRef<any>()
  const {
    role: { id },
    username,
    region
  } = JSON.parse(localStorage.getItem('token') || '')
  const switchMethods = (item: any) => {
    console.log(item.roleState)
    item.roleState = !item.roleState
    setDataSource([...dataSource])
    axios.patch(`/users/${item.id}`, { roleState: item.roleState })
  }
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render: (region: string) => <b>{region === '' ? '全球' : region}</b>,
      filters: [
        ...regionList.map((item: any) => {
          return { text: item.title, value: item.value }
        }),
        {
          text: '全球',
          value: '全球'
        }
      ],
      onFilter: (value: any, item: any) => {
        if (value === '全球') {
          return item.region === ''
        } else {
          return item.region === value
        }
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role: any) => {
        return role.roleName
      }
    },
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState: boolean, item: any) => (
        <Switch
          checked={roleState}
          defaultChecked
          disabled={item.default}
          onChange={() => {
            switchMethods(item)
          }}
        />
      )
    },
    {
      title: '操作',
      render: (item: any) => (
        <div>
          <Button
            danger
            shape="circle"
            icon={<DeleteOutlined />}
            onClick={() => showConfirm(item)}
            disabled={item.default}
          ></Button>

          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            disabled={item.default}
            onClick={() => {
              handleUpdate(item)
            }}
          ></Button>
        </div>
      )
    }
  ]

  useEffect(() => {
    let roleObj: any = {
      1: 'superdmin',
      2: 'admin',
      3: 'editor'
    }
    axios.get(`/users?_expand=role`).then((res) => {
      console.log(res.data)
      // if()
      let list = res.data
      setDataSource(
        roleObj[id] === 'superdmin'
          ? list
          : [
              ...list.filter((item2: any) => item2.username === username),
              ...list.filter((item: any) => item.region === region && roleObj[item.roleId] === 'editor')
            ]
      )
    })
  }, [id, region, username])
  useEffect(() => {
    axios.get(`/regions`).then((res) => {
      console.log(res.data)
      setRegionList(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get(`/roles`).then((res) => {
      console.log(res.data)
      setRoleList(res.data)
    })
  }, [])

  const showConfirm = (item: any) => {
    confirm({
      title: '您确定要删除?',
      icon: <ExclamationCircleFilled />,
      content: 'Some descriptions',
      onOk() {
        delMethods(item)
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }
  //删除
  const delMethods = (item: any) => {
    setDataSource(dataSource.filter((item2: any) => item2.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }
  //编辑
  const handleUpdate = (item: any) => {
    setUpdateVisble(true)
    setTimeout(() => {
      console.log(item, updateForm)
      if (item.roleId === 1) {
        //禁用
        setUpdateDisabled(true)
      } else {
        setUpdateDisabled(false)
      }
      updateForm.current.setFieldsValue({
        ...item
      })
    }, 200)
    setCurrent(item)
  }
  //确认添加
  const addFormMethods = () => {
    addForm.current.validateFields().then((res: any) => {
      console.log(res)
      // setFormValues([...res])
      setOpen(false)
      addForm.current.resetFieldValue()
      axios
        .post(`/users`, {
          ...res,
          roleState: true,
          default: false
        })
        .then((res) => {
          axios.get(`/users?_expand=role`).then((res) => {
            console.log(res.data)
            setDataSource(res.data)
          })
        })
    })
  }
  //确认编辑
  const updateFormOk = () => {
    updateForm.current.validateFields().then((res: any) => {
      setUpdateVisble(false)
      // setUpdateDisabled(!updateDisabled)
      // setDataSource
      axios.patch(`/users/${current.id}`, res).then((res) => {
        axios.get(`/users?_expand=role`).then((res) => {
          console.log(res.data)
          setDataSource(res.data)
        })
      })
    })
  }
  return (
    <div>
      <Button type="primary" onClick={() => setOpen(true)}>
        添加用户
      </Button>
      <Table dataSource={dataSource} columns={columns} rowKey="id" pagination={{ pageSize: 5 }} />
      <Modal
        open={open}
        title="Create a new collection"
        okText="Create"
        cancelText="Cancel"
        onOk={() => addFormMethods()}
        onCancel={() => setOpen(false)}
        destroyOnClose
      >
        <UserForm roleList={roleList} regionList={regionList} ref={addForm}></UserForm>
      </Modal>
      <Modal
        open={isUpdateVisble}
        title="更新用户"
        okText="确认"
        cancelText="Cancel"
        onOk={() => updateFormOk()}
        onCancel={() => {
          setUpdateVisble(false)
          // setUpdateDisabled(!isUpdateVisble)
        }}
        destroyOnClose
      >
        <UserForm
          roleList={roleList}
          regionList={regionList}
          ref={updateForm}
          isDisable={updateDisabled}
          isUpdate={true}
        ></UserForm>
      </Modal>
    </div>
  )
}
